package com.mingtu.jgspatrol.activity;

import static com.mingtu.common.utils.MyUtills.getBounds;
import static com.mingtu.jgspatrol.utils.MyConstant.INFO_WINDOW_OFF_SET_Y;
import static com.mingtu.jgspatrol.utils.MyConstant.MAX_ZOOM;

import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.activity.NaviMapActivity;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.SPTools;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.EcAdapter;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.EcDequiBean;
import com.mingtu.jgspatrol.databinding.ActivityEcologyMonitorBinding;
import com.mingtu.jgspatrol.utils.MarkerOptionsUtils;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EcologyMonitorActivity extends MyBaseActivity<ActivityEcologyMonitorBinding> implements AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener, AMap.OnMapTouchListener, AMap.OnMarkerClickListener {
    private AMap aMap;
    private List<Marker> markerList = new ArrayList<>();
    private ArrayList<Marker> dequiMarker = new ArrayList<>();
    private View infoWindow;
    private LatLng location;
    private Marker clickMarker;
    private int checkedPosition = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ecology_monitor;
    }

    @Override
    protected void initView() {
        setModuleTitle("生态监测");
        super.initView();
    }

    @Override
    protected void initData() {
        EcAdapter ecAdapter = new EcAdapter(context);
        binding.gridView.setAdapter(ecAdapter);
        ecAdapter.setOnItemClickListener(new EcAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == 0) {//实时监测
                    IntentUtils.getInstance().readyGo(EcologyMonitorActivity.this, EcRealtimeDataActivityNew.class);
                } else if (position == 1) {//设备管理
                    IntentUtils.getInstance().readyGo(EcologyMonitorActivity.this, EcDequipmentActivity.class);
                } else if (position == 2) {//大屏控制
                    IntentUtils.getInstance().readyGo(EcologyMonitorActivity.this, ScreenControlActivity.class);
                }
            }
        });
        addClickListener(this, binding.ivZoom);
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        binding.mapView.onCreate(savedInstanceState);
        aMap = binding.mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.addOnMapTouchListener(this);

        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                getDequiList();
            }
        });
        String longitude = SPStaticUtils.getString(SPTools.lng);
        String latitude = SPStaticUtils.getString(SPTools.lat);
        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
            location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz))
                    .infoWindowEnable(false);
            Marker marker = aMap.addMarker(markerOptions);
            markerList.add(marker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }
    }

    @Override
    protected void getData() {
        initPullRefresh();
    }

    @Override
    protected void onDestroy() {
        if (aMap != null) {
            binding.mapView.onDestroy();
        }

        if (markerList.size() > 0) {
            for (Marker marker : markerList) {
                marker.remove();
            }
            markerList.clear();
        }

        if (dequiMarker.size() > 0) {
            for (Marker marker : dequiMarker) {
                marker.remove();
            }
            dequiMarker.clear();
        }

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_zoom:
                IntentUtils.getInstance().readyGo(EcologyMonitorActivity.this, EcologyMapActivity.class);
                break;
        }
    }

    @Override
    public View getInfoWindow(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(this).inflate(R.layout.bubble_view2, null);
        }
        render(marker, infoWindow);
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        clickMarker = marker;
        return false;
    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
        if (clickMarker != null) {
            boolean b = clickMarker.isInfoWindowShown();
            if (b) {
                clickMarker.hideInfoWindow();
            }
        }
    }


    private void initPullRefresh() {
        binding.srlUp.setEnableLoadMore(false);
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                getDequiList();
            }
        });
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        String windowInfo = marker.getTitle();
        TextView title = ((TextView) view.findViewById(R.id.title));
        title.setText(windowInfo);
        LinearLayout layoutMarker = (LinearLayout) view.findViewById(R.id.layout);
        layoutMarker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //防止点击事件和touch事件冲突，所以采用此种方式跳转
                LatLng latLng = marker.getPosition();
                String lngStr = latLng.longitude + "";
                String latStr = latLng.latitude + "";
                Bundle bundle = new Bundle();
                bundle.putString("lng", lngStr);
                bundle.putString("lat", latStr);
                bundle.putBoolean("isFire", false);
                IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), NaviMapActivity.class, bundle);
            }
        });

    }

    /**
     * 设备列表
     */
    private void getDequiList() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceType", null);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_EC_DEVICE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            EcDequiBean ecDequiBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ecDequiBean = new EcDequiBean();
                                ecDequiBean = gson.fromJson(result, EcDequiBean.class);
                                List<EcDequiBean.DataBean> dataBeans = ecDequiBean.getData();

                                if (dataBeans != null) {
                                    int size = dataBeans.size();
                                    if (size > 0) {

                                        //气象
                                        ApplicationInfo appInfo1 = context.getApplicationInfo();
                                        ArrayList<BitmapDescriptor> weatherGif = new ArrayList<BitmapDescriptor>();
                                        for (int i = 1; i <= 24; i++) {
                                            int resID = getResources().getIdentifier("icon_ec" + i, "mipmap", appInfo1.packageName);
                                            weatherGif.add(BitmapDescriptorFactory.fromResource(resID));
                                        }


                                        //水文
                                        ApplicationInfo appInfo2 = context.getApplicationInfo();
                                        ArrayList<BitmapDescriptor> hydrologyGif = new ArrayList<BitmapDescriptor>();
                                        for (int i = 1; i <= 24; i++) {
                                            int resID = getResources().getIdentifier("icon_hydrology" + i, "mipmap", appInfo2.packageName);
                                            hydrologyGif.add(BitmapDescriptorFactory.fromResource(resID));
                                        }


                                        int offlineNum = 0;
                                        int onlineNum = 0;
                                        List<LatLng> latLngs = new ArrayList<>();
                                        for (int i = 0; i < size; i++) {
                                            EcDequiBean.DataBean dataBean = dataBeans.get(i);
                                            String latitude = dataBean.getLat();
                                            String longitude = dataBean.getLon();
                                            String heartTime = dataBean.getHeartTime();
                                            String status = dataBean.getStatus();
                                            String name = dataBean.getName();


                                            boolean isOnline = false;
                                            if (!StringUtils.isEmpty(status)) {
                                                if (status.equals("0")) { //0 离线  1在线
                                                    //如果当前时间与心跳时间的差值大于12小时，说明设备离线
                                                    isOnline = false;
                                                    offlineNum += 1;
                                                } else {
                                                    isOnline = true;
                                                    onlineNum += 1;
                                                }

                                            } else {
                                                if (!StringUtils.isEmpty(heartTime)) {
                                                    long hearTimeMillis = TimeUtils.string2Millis(heartTime);
                                                    long nowMills = TimeUtils.getNowMills();
                                                    if (nowMills - hearTimeMillis > 12 * 60 * 60 * 1000) {
                                                        //如果当前时间与心跳时间的差值大于12小时，说明设备离线
                                                        isOnline = false;
                                                        offlineNum += 1;
                                                    } else {
                                                        isOnline = true;
                                                        onlineNum += 1;
                                                    }
                                                }
                                            }

                                            if (!StringUtils.isEmpty(latitude) && !StringUtils.isEmpty(longitude)) {
                                                double lat = Double.parseDouble(latitude);
                                                double lng = Double.parseDouble(longitude);
                                                LatLng location = new LatLng(lat, lng);
                                                latLngs.add(location);
                                                //添加Marker
                                                if (isOnline) {
                                                    if (name.indexOf("气象") != -1) {
                                                        Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions2(location, name, INFO_WINDOW_OFF_SET_Y, weatherGif));
                                                        markerList.add(marker);
                                                    } else {
                                                        Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions2(location, name, INFO_WINDOW_OFF_SET_Y, hydrologyGif));
                                                        markerList.add(marker);
                                                    }

                                                } else {
                                                    if (name.indexOf("气象") != -1) {
                                                        Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions1(location, name, INFO_WINDOW_OFF_SET_Y, R.mipmap.icon_ec_offline));
                                                        markerList.add(marker);
                                                    } else {
                                                        Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions1(location, name, INFO_WINDOW_OFF_SET_Y, R.mipmap.icon_hydrology_offline));
                                                        markerList.add(marker);
                                                    }
                                                }
                                            }


                                        }
                                        binding.tvTotalNum.setText("设备总数：" + size + "台");
                                        binding.tvOnlineNum.setText("在线：" + onlineNum + "台");
                                        binding.tvOfflineNum.setText("离线：" + offlineNum + "台");

                                        if (latLngs.size() > 0) {
                                            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(latLngs), 200));
                                        }

                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }
}